package com.itheima.controller;

import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequestMapping("/clazzs")
@RestController
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private EmpService empService;

    //分页条件查询班级（使用MYbatis-plus）
    @GetMapping
    public Result page(ClazzQueryParam param) {
        log.info("班级列表查询条件：{}", param);


        PageResult<Clazz> pageResult = clazzService.getPageResult(param);
        // 返回结果
        return Result.success(pageResult);
    }

    @PostMapping
    public Result save(@RequestBody Clazz clazz) {
        log.info("新增班级：{}", clazz);
        // 调用service层方法保存班级信息
        // 补全基础属性
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.save(clazz);

        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询班级：{}", id);
        Clazz clazz = clazzService.getById(id);
        if (clazz == null) {
            // 返回一个自定义错误消息或使用Spring Boot的统一异常处理机制
            return Result.error("未找到指定ID的班级");
        }
        //班主任名称
        clazz.setMasterName(empService.getById(clazz.getMasterId()).getName());

        return Result.success(clazz);
    }

    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级：{}", clazz);
        // 调用service层方法修改班级信息
        // 根据id更新班级的基本信息
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.updateById(clazz);

        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除班级：{}", id);
        // 根据id删除班级的基本信息
        clazzService.removeById(id);

        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询全部班级");
        // 调用service层方法查询班级列表
        return Result.success(clazzService.list());
    }


}
